import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex)


export default new Vuex.Store({
  state: {
    cart: [],
    selectedItems: [] // 存储选中的商品ID
  },
  mutations: {
    addToCart(state, product) {
      state.cart.push(product);
    },
    removeFromCart(state, productId) {
      state.cart = state.cart.filter(item => item.id !== productId);
    },
    toggleSelectItem(state, productId) {
      if (state.selectedItems.includes(productId)) {
        state.selectedItems = state.selectedItems.filter(id => id !== productId);
      } else {
        state.selectedItems.push(productId);
      }
    }
  },
  actions: {
    addToCart({ commit }, product) {
      commit('addToCart', product);
    },
    removeFromCart({ commit }, productId) {
      commit('removeFromCart', productId);
    },
    toggleSelectItem({ commit }, productId) {
      commit('toggleSelectItem', productId);
    }
  },
  getters: {
    cartItems: state => state.cart,
    selectedItems: state => state.selectedItems,
    selectedTotalPrice: state => {
      return state.cart
        .filter(item => state.selectedItems.includes(item.id))
        .reduce((total, item) => total + item.price, 0);
    }
  }
});